package com.leetroll.api.handle;

import com.alibaba.fastjson.JSON;
import com.leetroll.api.service.UserService;
import com.leetroll.common.bean.ApiResponse;
import com.leetroll.common.entity.SysExceptionLog;
import com.leetroll.common.entity.User;
import com.leetroll.common.utils.IpUtils;
import com.leetroll.common.utils.UserUtil;
import com.leetroll.common.utils.exception.TransformUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 异常处理类【全局异常处理】
 */
@Slf4j
@Configuration
@RestControllerAdvice
public class HandlerExceptionResolver {

    @Autowired
    private UserService userService;

    /**
     * 异常处理方法
     * @param exception 出现的异常信息
     */
    @ExceptionHandler(Exception.class)
    public ApiResponse<?> resolveException(HttpServletRequest request, HttpServletResponse response, Exception exception) {
        log.error("系统统一异常处理：", exception);
        // 若响应已响应或已关闭，则不操作
        if (response.isCommitted()) {
            return ApiResponse.OK();
        }

        StackTraceElement stackTraceElement = exception.getStackTrace()[0];
        //用户登陆用户名
        Long userId= UserUtil.getUserId();
        String method = request.getMethod();
        String requestURI = request.getRequestURI();
        String reqParamsJson = JSON.toJSONString(TransformUtil.converMap(request.getParameterMap()));
        String ip = IpUtils.getIpAddr(request);

        //异常信息
        String errorInfo = exception.toString() + ",errorMassage:" + stackTraceElement + "," + "errorLine:" + stackTraceElement.getLineNumber();
        String exceptionName = exception.getClass().getName();
        String message =TransformUtil.stackTraceToString(exception.getClass().getName(), exception.getMessage(), exception.getStackTrace());

        SysExceptionLog exceptionLog = new SysExceptionLog();
        exceptionLog.setExceptionMessage(message);
        exceptionLog.setOperation(errorInfo);
        exceptionLog.setMethod(method);
        exceptionLog.setReqParam(reqParamsJson);
        exceptionLog.setIp(ip);
        exceptionLog.setUrl(requestURI);
        exceptionLog.setUserId(userId);
        exceptionLog.setExceptionName(exceptionName);
        exceptionLog.setExceptionType("info");

        //插入数据库
        exceptionLog.insert();

        // 响应类型设置
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        return ApiResponse.FAIL(exception.getMessage());

//        // 组装错误提示信息
//        String errorCode = ErrorCode.ERROR;
//        String message = MessageConstant.OPERATION_FAIL;
//
//        // 自定义业务相关异常
//        if (exception instanceof BusinessException) {
//            errorCode = ((BusinessException) exception).getCode();
//            message = exception.getMessage();
//        } else if (exception instanceof ApiInvalidParamException) {
//            // 自定义参数校验相关的异常
//            // 自动拼接异常信息
//            errorCode = ErrorCode.PARAM_INCORRECT;
//            message = exception.getMessage();
//        } else if (exception instanceof LoginException) {
//            // 自定义登录相关的异常
//            errorCode = ((LoginException) exception).getCode();
//            message = exception.getMessage();
//        } else if (exception instanceof QueryException) {
//            // 自定义查询相关的异常
//            errorCode = ((QueryException) exception).getCode();
//            message = exception.getMessage();
//        } else if (exception instanceof UpdateException) {
//            // 自定义更新操作相关的异常
//            errorCode = ((UpdateException) exception).getCode();
//            message = exception.getMessage();
//        } else if (exception instanceof InsertException) {
//            // 自定义新增操作相关的异常
//            errorCode = ((InsertException) exception).getCode();
//            message = exception.getMessage();
//        } else if (exception instanceof DeleteException) {
//            // 自定义删除操作相关的异常
//            errorCode = ((DeleteException) exception).getCode();
//            message = exception.getMessage();
//        } else {
//            // 其它异常
//            message = exception.getMessage();
//            log.error(exception.getMessage());
//        }
    }
}